package learn_concurrent._11;

import java.util.concurrent.atomic.AtomicStampedReference;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AtomicStampedReferenceTest {

	static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0);
	static Logger logger = LoggerFactory.getLogger(AtomicStampedReferenceTest.class);

	public static void main(String[] args) throws InterruptedException {
		String prev = ref.getReference();
		int stamp = ref.getStamp();
		logger.info("stamp : {}", stamp);

		otherThreadDoSomething();
		Thread.sleep(1000);
		boolean success = ref.compareAndSet(prev, "C", stamp, stamp + 1);
		logger.info("change A -> C : {}", success);
	}

	static void otherThreadDoSomething() throws InterruptedException {
		new Thread(() -> logger.info("change A -> B : {}",
				ref.compareAndSet(
						ref.getReference(), 
						"B", 
						ref.getStamp(), 
						ref.getStamp() + 1)), "t1").start();

		Thread.sleep(500);

		new Thread(() -> logger.info("change B -> A : {}",
				ref.compareAndSet(
						ref.getReference(), 
						"A", 
						ref.getStamp(), 
						ref.getStamp() + 1)), "t2").start();
	}

}
